const http=require('http')
// const url=require('url') 
// get请求 {pathname,query} 第二个参数true url.parse(req.url,true)
const bcrypt=require('bcrypt')
//querystring解析前端数据post请求 转化为query
const querystring=require('querystring')
const app=http.createServer()

let users=[]

app.on('request',function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain;charset=utf-8'});
  if (request.url=="/login") return login(request, response) 
  if (request.url=="/registry") return registry(request, response) 
  response.end('Hello World')
})

// let { pathname }=url.parse()
// console.log(request.method);

function registry(request, response) {
  let formData='';
  request.on('data',async function (params) {
    formData+=params;
  })
  request.on('end',async function () {
    let user=querystring.parse(formData)
    //这里有加密
    const hashedPassword=await bcrypt.hash(user.password,10)
    users.push({
      username:user.username,
      password:hashedPassword
    })
  })
  let loginPage=`
  <!doctype html>
<html lang="en">
  <head>
    <title>Title</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  </head>
  <body>
      
    <div class="container">
      <div class="row">
        <div class="col mt-3">
          <form method="post" action="http://127.0.0.1:3000/login">
            <label for="username">username:</label>
            <input class="form-control" id="username" type="text" name="username">
            <label for="password">password:</label>
            <input class="form-control" id="password" type="password" name="password">
            <div class="mt-3"> <button type="submit" class="btn btn-primary">login</button>
              <a href="/registry.html"><button type="button" class="btn btn-warning">registry</button></a></div>
          </form>
        </div>
      </div>
    </div>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
  </body>
</html>`
  response.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});  
  response.end(loginPage)
}
function login(request, response){
  let formData=''
  request.on('data',async (params)=>{
    formData+=params
  })
  request.on('end',async ()=>{
    let user=querystring.parse(formData)
    const item=users.find(item=>item.username===user.username)
    console.log(item);
    if (item==null) return response.end('username not found')
    if (await bcrypt.compare(user.password,item.password)) {
      return response.end('login success')
    }else{
      response.end('password incorrect')
    }
  })
}
app.listen(3000,'localhost',function(){
  console.log('Server running at http://127.0.0.1:3000/')
})


/* 
1.const salt=await bcrypt.genSalt(10);
2.const hashedPassword=await bcrypt.hash(user.password,salt)
*/ 